/*
 * @Date: 2024-01-05 08:59:20
 * @LastEditors: lyx
 * @LastEditTime: 2024-01-09 15:09:50
 * @FilePath: \chlor-alkali-cloud-mobile-end\src\utils\api.ts
 * @Description:
 */
import axios from "axios";
import { TaroAdapter } from "axios-taro-adapter";
import Taro from "@tarojs/taro";
import resultFormat from "./requestFormat/resultFormat";
import errorHandler from "./requestFormat/errorFormat";
import { toLogin } from "./common";

const showErrorToast = (msg) => {
  Taro.showToast({
    title: msg,
    icon: "none",
  });
};

// 处理  类型“AxiosResponse<any, any>”上不存在属性“errorinfo”。ts(2339) 脑壳疼！关键一步。
// Axios响应模式如下所示：
// {
//   data: {},
//   status: 200,
//   statusText: 'OK',
//   headers: {},
//   config: {},
//   request: {}
// }
declare module "axios" {
  interface AxiosResponse<T = any> {
    content: any;
    msg: any;
    code: any;
    url?: string;
  }
  export function create(config?: AxiosRequestConfig): AxiosInstance;
}

const default_options = {
  responseType: "json",
  "Content-Type": "application/json;charset=utf-8",
};

const SupRequest = axios.create({
  baseURL: "",
  timeout: 600000,
  adapter: TaroAdapter, // add this line，添加这一行使用taroAdapter
});

async function resolveResponse(requestOptions: any, response: Response) {
  if (requestOptions?.config?.responseType === "blob") {
    const data = await response.blob();
    return { data, response };
  } else if (requestOptions?.config?.responseType === "arrayBuffer") {
    const data = await response.arrayBuffer();
    return { data, response };
  } else if (requestOptions?.config?.responseType === "formData") {
    const data = await response.formData();
    return { data, response };
  } else if (requestOptions?.config?.responseType === "text") {
    const data = await response.text();
    return { data, response };
  } else {
    const data = response?.data ?? {};
    const result = requestOptions.formatResult
      ? resultFormat(data, requestOptions, response)
      : data;
    return result;
  }
}

// request拦截器
SupRequest.interceptors.request.use(
  (config: any) => {
    console.log("config", config);
    Taro.showLoading({
      title: "加载中",
      mask: true,
    });
    let token = Taro.getStorageSync("token");
    let platform = Taro.getStorageSync("platform");
    let language = Taro.getStorageSync("language");
    console.log("token", token);
    config = {
      responseType: "json",
      ...config,
    };
    config.headers = {
      ...default_options,
      platform,
      "Accept-Language": language ?? "en-us",
      ...config.headers,
    };
    // 判断是否携带token: 部分鉴权接口不需要携带 Authorization 参数
    if (!config?.notCarryAuthority) {
      if (typeof token == "undefined") {
        token = "";
      }
      config.headers = {
        ...config.headers,
        Authorization: `Bearer ${token || ""}`,
      };
    }
    return config;
  },
  (error) => {
    // Do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// respone拦截器
SupRequest.interceptors.response.use(
  (response: any) => {
    console.log("response", response);
    Taro.hideLoading();
    if (response?.status === 200 || response.status === 401) {
      if (response?.config?.responseType !== "json") {
        resolveResponse(response, response);
      } else {
        const data = response?.data;
        console.log("data json", data);
        if (data?.code === "A0230") {
          // 登录失效
          console.log("登录失效");
          // toLogin()
        } else {
          // 对返回数据进行格式化
          return resolveResponse(response, response);
        }
      }
    } else {
      return errorHandler(response);
    }

    // if (response.data.isError) {
    //   showErrorToast(response.data.error.message);
    //   if (response.data.error.codeNumber === "A0230") {
    //     // 登录失效
    //     Taro.navigateTo({
    //       url: "/pages/login/index",
    //     });
    //   }
    // } else {
    //   return response.data;
    // }
  },
  (error) => {
    Taro.hideLoading();
    console.log("error", error); // for debug
    showErrorToast(error.message);
    return Promise.reject(error);
  }
);

export default SupRequest;
